package com.sxhuayuan.parking.controller.admin;

import com.sxhuayuan.parking.compenent.Message;
import com.sxhuayuan.parking.compenent.Page;
import com.sxhuayuan.parking.compenent.Pageable;
import com.sxhuayuan.parking.controller.BaseController;
import com.sxhuayuan.parking.entity.Settings;
import com.sxhuayuan.parking.service.SettingsService;
import org.springframework.validation.BindingResult;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import com.sxhuayuan.parking.compenent.web.RespMessage;
import com.sxhuayuan.parking.utils.SettingUtils;

import javax.annotation.Resource;
import java.util.Date;

@RestController
@RequestMapping("/admin/setting")
public class SettingController extends BaseController {

	@Resource(name = "settingsServiceImpl")
	SettingsService settingsService;

	@RequestMapping("get")
	public RespMessage get() {
		return RespMessage.builder().success().setDatas(SettingUtils.get()).build();
	}

	/**
	 * 系统设置分页查询
	 * 
	 * @param pageable
	 *            分页条件
	 * @return 返回分页列表
	 */
	@RequestMapping("/variable")
	public RespMessage variable(@RequestBody Pageable pageable) {
		Page<Settings> page = settingsService.findPage(pageable);
		return RespMessage.builder().success().setDatas(page).build();
	}

	/**
	 * 新增系统设置
	 * 
	 * @param settings
	 *            设置
	 * @param bindingResult
	 *            校验信息
	 * @return 成功状态
	 */
	@PostMapping("/save")
	public RespMessage save(@RequestBody @Validated Settings settings, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return RespMessage.error(RespMessage.Status.VALID_ERR, Message.FORM_VALID_FAIL);
		}
		settings.setCreateDate(new Date());
		settings.setModifyDate(new Date());
		settingsService.save(settings);
		return RespMessage.success(null, "成功");
	}

	/**
	 * 删除指定id的数据
	 * 
	 * @param id
	 *            id
	 * @return 状态
	 */
	@PostMapping("/delete/{id}")
	public RespMessage delete(@PathVariable Long id) {
		Settings one = settingsService.findOne(id);
		if (one == null) {
			return RespMessage.error("数据不存在");
		}
		settingsService.delete(id);
		return RespMessage.success("删除成功");
	}

	/**
	 * 修改系统设置
	 * 
	 * @param settings
	 *            数据
	 * @param bindingResult
	 *            校验
	 * @return 状态
	 */
	@PostMapping("/update")
	public RespMessage update(@RequestBody @Validated Settings settings, BindingResult bindingResult) {
		if (bindingResult.hasErrors()) {
			return RespMessage.error(RespMessage.Status.VALID_ERR, Message.FORM_VALID_FAIL);
		}
		if (settings.getId() == null) {
			return RespMessage.error("id不能为空");
		}
		Settings one = settingsService.findOne(settings.getId());
		if (one == null) {
			return RespMessage.error("数据不存在");
		}

		settings.setModifyDate(new Date());
		settingsService.update(settings);
		return RespMessage.success("成功");
	}
}
